import { student, addstudent, deletestudent, updatestudent } from '@/services/ant-design-pro';
import { PlusOutlined } from '@ant-design/icons';
import {
    ActionType,
    ProColumns,
    ProFormInstance,
} from '@ant-design/pro-components';
import {
    ModalForm,
    PageContainer,
    ProFormTextArea,
    ProTable,
} from '@ant-design/pro-components';
import { FormattedMessage } from '@umijs/max';
import { Button, message, Popconfirm } from 'antd';
import React, { useRef, useState } from 'react';

/**
 * @en-US Add node
 * @zh-CN 添加节点
 * @param fields
 */
const handleAdd = async (fields: API.RuleListItem) => {
    const hide = message.loading('正在添加');
    try {
        await addstudent({ ...fields });
        hide();
        message.success('Added successfully');
        return true;
    } catch (error) {
        hide();
        message.error('Adding failed, please try again!');
        return false;
    }
};

/**
 * @en-US Update node
 * @zh-CN 更新节点
 *
 * @param fields
 */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const handleUpdate = async (fields: any) => {
    const hide = message.loading('Configuring');
    try {
        await updatestudent({
            ...fields,
            id: fields.id,
        });
        hide();

        message.success('Configuration is successful');
        return true;
    } catch (error) {
        hide();
        message.error('Configuration failed, please try again!');
        return false;
    }
};

const TableList: React.FC = () => {
    const updateFormRef = useRef<ProFormInstance>();
    /**
     * @en-US Pop-up window of new window
     * @zh-CN 新建窗口的弹窗
     *  */
    const [createModalVisible, handleModalVisible] = useState<boolean>(false);
    /**
     * @en-US The pop-up window of the distribution update window
     * @zh-CN 分布更新窗口的弹窗
     * */
    const [currentRow, setCurrentRow] = useState<any>();
    const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

    const actionRef = useRef<ActionType>();
    const confirmDeleteFactor = async (record: any) => {
        try {
            const { success } = await deletestudent(record);
            if (success) {
                if (actionRef.current) {
                    actionRef.current.reload();
                }
            }
            message.success('Click on Yes');
        } catch (error) {
            message.error('Delete failed, please try again!');
            return false;
        }
    };
    const columns: ProColumns<any>[] = [
        {
            title: '学生id',
            dataIndex: 'StuId',
        },
        {
            title: '学生姓名',
            dataIndex: 'name',
        },
        {
            title: '学号',
            dataIndex: 'StuNumber',
        },
        {
            title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="Operating" />,
            key: 'option',
            valueType: 'option',
            render: (_, record) => {
                return [
                    <a key="edit" onClick={() => {
                        handleUpdateModalVisible(true)
                        setCurrentRow(record)
                    }}>
                        编辑
                    </a>,
                    <Popconfirm
                        title="你确定要删除该学生吗?"
                        onConfirm={() => confirmDeleteFactor(record)}
                        okText="Yes"
                        cancelText="No"
                        key={record.id}
                    >
                        <a key="subscribeAlert">删除学生</a>
                    </Popconfirm>,
                ];
            },
        },
    ];

    return (
        <PageContainer>
            <ProTable<any, API.PageParams>
                headerTitle={'学生管理'}
                actionRef={actionRef}
                rowKey="id"
                search={{
                    labelWidth: 120,
                }}
                toolBarRender={() => [
                    <Button
                        type="primary"
                        key="primary"
                        onClick={() => {
                            handleModalVisible(true);
                        }}
                    >
                        <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="New" />
                    </Button>,
                ]}
                request={student}
                columns={columns}
            />
            <ModalForm
                formRef={updateFormRef}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 16 }}
                layout={'horizontal'}
                title={'新增学生'}
                width="600px"
                visible={createModalVisible}
                onVisibleChange={(visible) => {
                    handleModalVisible(visible);
                }}
                onFinish={async (value) => {
                    const success = await handleAdd(value as API.RuleListItem);
                    if (success) {
                        handleModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
            >
                <ProFormTextArea
                    label={'学号'}
                    rules={[
                        {
                            required: true,
                            message: '学号为必选项',
                        },
                    ]}
                    width="md"
                    name="StuNumber"
                />
                <ProFormTextArea
                    label={'学生姓名'}
                    rules={[
                        {
                            required: true,
                            message: '学生姓名为必选项',
                        },
                    ]}
                    width="md"
                    name="name"
                />
                <ProFormTextArea
                    label={'性别'}
                    
                    width="md"
                    name="sex"
                />
                <ProFormTextArea
                    label={'证件号码'}
                    
                    width="md"
                    name="ZJH"
                />
                <ProFormTextArea
                    label={'联系电话'}
                    
                    width="md"
                    name="LXDH"
                />
            </ModalForm>
            <ModalForm
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 16 }}
                layout={"horizontal"}
                title={"修改学生信息"}
                initialValues={{ ...(currentRow || {}) }}
                width="600px"
                visible={updateModalVisible}
                onVisibleChange={visible => {
                    handleUpdateModalVisible(visible)
                    if (visible) {
                        updateFormRef.current?.setFieldsValue({
                            ...currentRow
                        })
                    } else {
                        setCurrentRow(undefined)
                    }
                }}
                onFinish={async (value) => {
                    const success = await handleUpdate({ ...currentRow, ...value as any, });
                    if (success) {
                        handleUpdateModalVisible(false);
                        if (actionRef.current) {
                            actionRef.current.reload();
                        }
                    }
                }}
            >
                <ProFormTextArea
                    label={'学号'}
                    rules={[
                        {
                            required: true,
                            message: '学号为必选项',
                        },
                    ]}
                    width="md"
                    name="StuNumber"
                />
                <ProFormTextArea
                    label={'学生姓名'}
                    rules={[
                        {
                            required: true,
                            message: '学生姓名为必选项',
                        },
                    ]}
                    width="md"
                    name="name"
                />
                  <ProFormTextArea
                    label={'性别'}
                    
                    width="md"
                    name="sex"
                />
                <ProFormTextArea
                    label={'证件号码'}
                    
                    width="md"
                    name="ZJH"
                />
                <ProFormTextArea
                    label={'联系电话'}
                    
                    width="md"
                    name="LXDH"
                />
            </ModalForm>
        </PageContainer>
    );
};

export default TableList;
